/**
 * 地图绘制圈工具
 * @param opts
 * @return
 * @constructor
 */
var DrawRadarRangeCircle = function(opts) {
    var ckTemplate = {
        // 图层对象
        map: null,
        // 经度纬度
        lon: null,
        lat: null,
        // 图层名称
        name: null,
        // 象限对象
        quadrantFeature: null,
        // 圆圈对象
        circles: null,
        // 线圈像素
        width: null,
        // 绘制文字
        drawTexts: null,
        // 图层对象
        circularVectorLayer: null,
        // 图层矢量层源
        circularVectorLayerSource: null,

        init: function () {
            const thas = this;
            if(!opts.map){
                alert("DrawRadarRangeCircle: map 对象不能为空！");
                return;
            }
            // 初始化数据
            this.map = opts.map;
            this.lon = opts ? opts.lon : null;
            this.lat = opts ? opts.lat : null;
            this.name = opts ? opts.name : null;
            this.quadrantFeature = opts ? opts.quadrantFeature : null;
            this.circles = opts ? opts.circles : null;
            this.width = opts ? opts.width : 3;
            this.drawTexts = opts ? opts.drawTexts : null;

            // 创建图层矢量层源
            this.circularVectorLayerSource = new ol.source.Vector({wrapX: false});
            // 创建图层
            this.circularVectorLayer = new ol.layer.Vector({
                name: thas.name,
                source: this.circularVectorLayerSource,
                zIndex: 2
            });
            // 添加图层到对象
            this.map.addLayer(this.circularVectorLayer);

            // 添加象限
            if(this.quadrantFeature){
                this.addQuadrantFeature(this.lon, this.lat, this.quadrantFeature.radius, this.quadrantFeature.angles);
            }
            // 添加圆圈
            if(this.circles){
                for (let key in this.circles) {
                    const circle = this.circles[key];
                    this.drawSector(
                        circle.radius,
                        circle.fx,
                        circle.angle,
                        circle.colorFill,
                        circle.colorCircle,
                        circle.line
                    );
                }
            }
            // 绘制文字
            if (this.drawTexts) {
                for (let key in this.drawTexts) {
                    const drawText = this.drawTexts[key];
                    this.drawText(
                        drawText.lon,
                        drawText.lat,
                        drawText.text,
                        drawText.font
                    );
                }
            }

            /*var circles = [
                {radius: 50, width: 1, color: "blue"},
                {radius: 100, width: 1, color: "red"},
                {radius: 150, width: 1, color: "blue"},
                {radius: 200, width: 1, color: "red"},
                {radius: 230, width: 2, color: "blue"}];*/

            /*var circles = [
                {radius: 15, width: 3, color: "#FDC102"},
                {radius: 50, width: 3, color: "#D86967"},
                {radius: 70, width: 3, color: "#4EB7D9"},
                {radius: 120, width: 3, color: "#92FEB7"}
            ];
            for (var i = 0; i < circles.length; i++) {
                this.addCircularFeature(this.lon, this.lat, circles[i]);
            }*/

            // this.drawSector(120,0,360,'rgba(255,192,0, 0.3)','#FDC102',true);

            /*this.drawSector(110,0,360,'rgba(217,102,102,0.25)','#C00000',true);
            this.drawSector(80,0,360,'rgba(255,122,255,0.25)','#FF00FF',true);
            this.drawSector(50,0,360,'rgba(149,255,185,0.25)','#66FF99',true);
            this.drawSector(20,0,360,'rgba(255,192,0,0.25)','#FDC102',true);*/

            // this.drawSector(120,221,270,'rgba(149,255,185, 0)','#66FF99');
            // this.drawSector(120,221,270,'rgb(255,122,255,0)','#FF00FF');
            // this.drawSector(75,221,270,'rgba(149,255,185, 0)','#0099CC');
            // this.drawSector(50,221,270,'rgba(217,102,102, 0)','#C00000');

            /*this.drawText(118.8,27.3, '非作业区', 'bold 26px normal');
            this.drawText(117.2,27.5, 'A2', 'bold 26px normal');
            this.drawText(117.5,27.45, 'B2', 'bold 26px normal');
            this.drawText(117.75,27.41, 'C2', 'bold 26px normal');

            this.drawText(117.35,27.0, 'A1', 'bold 26px normal');
            this.drawText(117.55,27.13, 'B1', 'bold 26px normal');
            this.drawText(117.8,27.22, 'C2', 'bold 26px normal');

            this.drawText(117.6,26.6, 'A3', 'bold 26px normal');
            this.drawText(117.8,26.9, 'B3', 'bold 26px normal');
            this.drawText(117.9,27.0, 'C3', 'bold 26px normal');*/

        },
        /**
         * 计算面积
         * @param polygon
         * @returns {string}
         */
        formatArea: function (polygon) {
            let area;
            const geom = /** @type {ol.geom.Polygon} */(polygon.clone().transform(
                this.map.getView().getProjection(), 'EPSG:4326'));
            const coordinates = geom.getLinearRing(0).getCoordinates();
            const wgs84Sphere = new ol.Sphere(6378137.0);
            area = Math.abs(wgs84Sphere.geodesicArea(coordinates));
            let output;
            if (area > 10000) {
                output = (Math.round(area / 1000000 * 100) / 100) + ' km²';
            } else {
                output = (Math.round(area * 100) / 100) + ' m²';
            }
            return output;
        },
        /**
         * 绘制范围圈
         * @param lon 中心点经度
         * @param lat 中心点纬度
         * @param radius_m 半径（米）
         */
        addCircularFeature:  function (lon, lat, circle){
            let geom = new ol.geom.Polygon.circular(new ol.Sphere(6378137),
                [lon, lat], circle.radius * 1000, 64);
            geom = geom.transform('EPSG:4326', this.map.getView().getProjection());

            const feature = new ol.Feature({
                geometry: geom,
                name: 'is circular',
                styles: []
            });
            feature.setStyle(new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: circle.color,
                    width: circle.width
                })
            }));

            this.circularVectorLayerSource.addFeature(feature);

            //添加范围圈标注
            var textGeom = new ol.geom.Point([lon, lat]);
            textGeom = textGeom.transform('EPSG:4326', this.map.getView().getProjection());
            var textFeature = new ol.Feature({
                geometry: textGeom,
                name: 'is point',
                styles:[]
            });
            textFeature.setStyle(new ol.style.Style({
                text: new ol.style.Text({
                    font: '15px Microsoft YaHei',
                    text: circle.radius_m + 'KM',
                    fill: new ol.style.Fill({
                        color: '#222'
                    })
                })
            }));
            this.circularVectorLayerSource.addFeature(textFeature);
        },
        /**
         * 绘制象限
         * @param lon
         * @param lat
         * @param radius
         * @param angles
         */
        addQuadrantFeature:  function (lon, lat, radius, angles){
            if(!angles){
                angles = [0, 90, 180, 270];
            }
            for (let i = 0; i < angles.length; i++) {
                const km1Text = this.computeCirclularFlight(lon, lat, radius * 1000, angles[i], angles[i]);
                let geom = new ol.geom.LineString(
                    [[lon, lat], [km1Text[0] * 1.0, km1Text[1] * 1.0]]);
                geom = geom.transform('EPSG:4326', this.map.getView().getProjection());
                const feature = new ol.Feature({
                    geometry: geom
                });
                this.circularVectorLayerSource.addFeature(feature);
            }
        },
        /**
         * 计算半径线
         * 经度、纬度、半径、开始角度、结束夹角度
         * @param lon
         * @param lat
         * @param radius
         * @param startAngle
         * @param endAngle
         * @returns {*[]}
         */
        computeCirclularFlight: function(lon, lat, radius,startAngle,endAngle) {
            const Ea = 6378137;      //   赤道半径
            const Eb = 6356725;      // 极半径
            const positionArr = [];
            //需求正北是0° cesium正东是0°
            for (let i = parseInt(startAngle); i <= parseInt(endAngle); i++) {
                const dx = radius * Math.sin(i * Math.PI / 180.0);
                const dy = radius * Math.cos(i * Math.PI / 180.0);

                const ec = Eb + (Ea - Eb) * (90.0 - lat) / 90.0;
                const ed = ec * Math.cos(lat * Math.PI / 180);

                const BJD = parseFloat(lon) + parseFloat((dx / ed) * 180.0 / Math.PI);
                const BWD = parseFloat(lat) + parseFloat((dy / ec) * 180.0 / Math.PI);

                positionArr.push(BJD+"");
                positionArr.push(BWD+"");
            }
            return positionArr;
        },
        /**
         * 字符串面转ol面
         * @param polygonStr
         * @param lon
         * @param lat
         * @returns {*[][]}
         */
        geoPolygonToOlPolygon: function (polygonStr,lon,lat) {
            const polygon = [];
            let n = 0;
            const j = polygonStr.length / 2;
            if(lon && lat){
                polygon[0] = [];
                polygon[0][0] = lon;
                polygon[0][1] = lat;
                n++;
            }
            for (let i = 0; i < j; i++) {
                polygon[i+n] = [];
                polygon[i+n][0] = Number(polygonStr[i*2]);
                polygon[i+n][1] = Number(polygonStr[i*2+1]);
            }
            if(lon && lat){
                polygon[j+n] = [];
                polygon[j+n][0] = lon;
                polygon[j+n][1] = lat;
            }
            return [polygon];
        },
        /**
         * 绘制扇形
         * @param radius
         * @param startAngle
         * @param endAngle
         * @param colorFill
         * @param colorCircle
         * @param line
         */
        drawSector: function (radius,startAngle,endAngle,colorFill,colorCircle,line){
            var thas = this;
            if(!colorFill){
                colorFill = 'rgba(255, 0, 0, 0.2)';
            }
            if(!colorCircle){
                colorCircle = '#ffcc33';
            }
            var miang = this.computeCirclularFlight(this.lon,this.lat,radius * 1000,startAngle,endAngle);
            var polygons = null;
            if(line){
                polygons = this.geoPolygonToOlPolygon(miang);
            }else {
                polygons = this.geoPolygonToOlPolygon(miang,this.lon,this.lat);
            }
            console.log(this.formatArea(new ol.geom.Polygon(polygons)));
            // 创建feature
            var feature = new ol.Feature({
                geometry: new ol.geom.Polygon(polygons)
            });
            var style = new ol.style.Style({
                fill: new ol.style.Fill({
                    color: colorFill
                }),
                stroke: new ol.style.Stroke({
                    color: colorCircle,
                    width: thas.width
                }),
                image: new ol.style.Circle({
                    radius: thas.width,
                    fill: new ol.style.Fill({
                        color: colorCircle
                    })
                })
            });
            feature.setStyle(style);
            this.circularVectorLayerSource.addFeature(feature);
        },
        /**
         * 绘制文本
         * @param lon
         * @param lat
         * @param text
         * @param font
         */
        drawText: function (lon, lat, text, font){
            // 创建样式
            var style = new ol.style.Style({
                text: new ol.style.Text({
                    text: text,
                    // font: "18px",
                    font: font,
                    textAlign: "center",
                    textBaseline: "middle",
                    fill: new ol.style.Fill({
                        color: "#000000"
                    }),
                })
            });
            // 创建要素，设置其样式
            var feature = new ol.Feature({
                geometry: new ol.geom.Point([lon, lat])
            });
            feature.setStyle(style);
            this.circularVectorLayerSource.addFeature(feature);
        },
        /**
         * 显示
         */
        show: function(){
            if(this.circularVectorLayer){
                this.circularVectorLayer.setVisible(true);
            }
        },
        /**
         * 影藏
         */
        hide: function(){
            if(this.circularVectorLayer){
                this.circularVectorLayer.setVisible(false);
            }
        },
        /**
         * 销毁
         */
        destroy: function(){
            if(this.circularVectorLayer){
                this.map.removeLayer(this.circularVectorLayer);
            }
        }
    };

    return (function init() {
        ckTemplate.init();
        return ckTemplate;
    })();
};
// 示例
/*var drawRadarRangeCircle = new DrawRadarRangeCircle({
    map: map,
    lon: 102.262967,
    lat: 27.873464,
    name: "drawRadarRangeCircle",
    width: 1,
    quadrantFeature: {
        radius: 110,
        angles: [90, 180, 270]
    },
    circles: [
        {
            radius: 110,
            fx: 0,
            angle: 360,
            colorFill: 'rgba(217,102,102,0.25)',
            colorCircle: '#C00000',
            line: true
        },
        {
            radius: 80,
            fx: 0,
            angle: 360,
            colorFill: 'rgba(255,122,255,0.25)',
            colorCircle: '#FF00FF',
            line: true
        },
        {
            radius: 50,
            fx: 0,
            angle: 360,
            colorFill: 'rgba(149,255,185,0.25)',
            colorCircle: '#66FF99',
            line: true
        },
        {
            radius: 20,
            fx: 0,
            angle: 360,
            colorFill: 'rgba(255,192,0,0.25)',
            colorCircle: '#FDC102',
            line: true
        },
    ],
    drawTexts: [
        {lon: 118.8, lat: 27.3, text: '非作业区', font: 'bold 26px normal'},
        {lon: 117.2, lat: 27.5, text: 'A2', font: 'bold 26px normal'},
    ]
});*/
